/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Form;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import core.DriverManager;
import core.ScreenEngine;
import network.Connection;
import network.PacketBuilder;
import view.additional.CellItem;
import view.additional.ThumbList;
import view.additional.TickerRenderer;
import view.commands.BackCommand;

/**
 *
 * @author Kvest
 */
public class DispetchingOfficeForm extends Form 
{
    private static final int OK_COMMAND_ID = 1;
    private static final int CALL_TO_CLIENT_ID = 0;
    private static final int CALL_TO_ME_ID = 1;
    private static final int CANCEL_ORDER_ID = 2;
    private static final int RECALL_ID = 3;
    private static final int SEND_MESSAGE_ID = 4;
            
    private ThumbList items;
    private Command ok;
    
    private CellItem callToClientItem;
    private CellItem callToMeItem;
    private CellItem cancelOrderItem;
    private CellItem recallItem;
    private CellItem sendMessageItem;
    
    private SendMessageForm sendMessageForm;
    
    public DispetchingOfficeForm()
    {
        super("dispetching_office");
        
        init();
        
        DriverManager.getManager().setTimerTimeoutListener(new Runnable() 
        {
            public void run() 
            {
                if (DriverManager.getManager().isShowRecallItem())
                {
                    boolean hasOrder = (DriverManager.getManager().getCurrentOrderID() != DriverManager.UNKNOWN_VALUE);
                    if (!contains(recallItem) && hasOrder)
                    {
                        items.addItem(recallItem);
                    }
                }
                else
                {
                    for (int i = items.size() - 1; i >= 0; --i)
                    {
                        if (items.getModel().getItemAt(i) == recallItem)
                        {
                            items.getModel().removeItem(i);
                            break;
                        }
                    }
                }
                
                repaint();
            }
        });
    }
    
    private void init()
    {
        setLayout(new BorderLayout());
        setScrollable(false);
        
        //Создаем список
        items = new ThumbList();
        items.setSelectCommandText("...");
        items.setFixedSelection(ThumbList.FIXED_NONE_CYCLIC);
        TickerRenderer render = new TickerRenderer();
        items.setRenderer(render);
        
        callToClientItem = new CellItem(CALL_TO_CLIENT_ID, "call_to_client");
        callToMeItem = new CellItem(CALL_TO_ME_ID, "call_to_me");
        recallItem = new CellItem(RECALL_ID, "recall");
        cancelOrderItem = new CellItem(CANCEL_ORDER_ID, "cancel_order");
        sendMessageItem = new CellItem(SEND_MESSAGE_ID, "send_message");
        addComponent(BorderLayout.CENTER, items);
        
        //Команды
        ok = new Command("ok",OK_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                selectAction();
                
                evt.consume();
            }
        };
        addCommand(ok);
        
        items.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt) 
            {
                ok.actionPerformed(evt);
            }
        });
        
        addCommand(new BackCommand());
    }
    
    private void setItems()
    {
        //Чистим список
        while (items.size() > 0)
        {
            items.getModel().removeItem(0);
        }
        
        boolean hasOrder = (DriverManager.getManager().getCurrentOrderID() != DriverManager.UNKNOWN_VALUE);
        if (hasOrder)
        {
//            items.addItem(callToClientItem);
        }
        items.addItem(callToMeItem);
        if (hasOrder)
        {
            items.addItem(cancelOrderItem);
            
            if (DriverManager.getManager().isShowRecallItem())
            {
                items.addItem(recallItem);
            }
        }
        items.addItem(sendMessageItem);
    }
    
    public void show()
    {
        setItems();
        
        super.show();
    }
    
    private void selectAction()
    {
        CellItem selected = (CellItem)items.getSelectedItem();
        
        if (selected == null)
        {
            return;
        }
        
        switch(selected.getId())
        {
            case CALL_TO_CLIENT_ID : callToClientRequest(); break;
            case CALL_TO_ME_ID : callToMeRequest(); break;
            case CANCEL_ORDER_ID : cancelOrderRequest(); break;
            case RECALL_ID : recallRequest(); break;    
            case SEND_MESSAGE_ID : showSendMessageForm(); break;
        }
    }
    
    private void callToClientRequest()
    {
        byte[] data = PacketBuilder.createCallToClientRequest(DriverManager.getManager().getDriverID(),DriverManager.getManager().getCurrentOrderID());
        sendReques(data);
    }
    
    private void callToMeRequest()
    {
        byte[] data = PacketBuilder.createCallToMeRequest(DriverManager.getManager().getDriverID());
        sendReques(data);
    }
    
    private void recallRequest()
    {
        byte[] data = PacketBuilder.createReacallRequest(DriverManager.getManager().getDriverID(),DriverManager.getManager().getCurrentOrderID());
        sendReques(data);
    }
    
    private void cancelOrderRequest()
    {
        byte[] data = PacketBuilder.createCancelOrderRequest(DriverManager.getManager().getDriverID(),DriverManager.getManager().getCurrentOrderID());
        sendReques(data);
    }
    
    private void sendReques(byte[] data)
    {
        //Отображаем форму прогресса
        ScreenEngine.getEngine().push(new ProgressForm());
        
        //отправляем запрос
        boolean result = Connection.getConnection().send(data);
        
        //Переходим на главную форму
        ScreenEngine.getEngine().popTo(0);
        
        //Отображаем сообщение если произошла ошибка
        if (!result)
        {
            MessageBox.showModeless("message", "request_error");
        }
    }
    
    private void showSendMessageForm()
    {
        //Создаем форму
        if (sendMessageForm == null)
        {
            sendMessageForm = new SendMessageForm();
        }
        
        //Чистим форму
        sendMessageForm.clean();
        
        //Отображаем
        ScreenEngine.getEngine().push(sendMessageForm);
    }
}
